<template>
  <XenPageLayout
    title="应用管理"
    title-align="left"
    :show-back="true"
    navbar-bg-color="#6366f1"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
  >
    <!-- 主体内容 -->
    <view class="menu-container">
      <!-- 搜索区域 -->
      <view class="search-section">
        <view class="search-box">
          <uni-icons type="search" size="20" color="#999"></uni-icons>
          <input
            v-model="searchKeyword"
            placeholder="搜索应用..."
            class="search-input"
            @input="handleSearch"
          />
        </view>
      </view>

      <!-- 应用分类 -->
      <view class="category-section">
        <view class="category-header">
          <view class="header-icon">
            <i
              class="iconfont icon-gongwenbao"
              style="font-size: 14px; color: #6366f1"
            ></i>
          </view>
          <text class="section-title">应用分类</text>
        </view>
        <scroll-view class="category-list" scroll-x :show-scrollbar="false">
          <view class="category-wrapper">
            <view
              v-for="category in displayCategories"
              :key="category.id"
              :class="[
                'category-item',
                { active: selectedCategory === category.id },
              ]"
              @click="selectCategory(category.id)"
            >
              <view class="category-icon">
                <i
                  :class="
                    category.icon.startsWith('icon-')
                      ? `iconfont ${category.icon}`
                      : `iconfont icon-${category.icon}`
                  "
                  :style="{
                    fontSize: '18px',
                    color:
                      selectedCategory === category.id ? '#ffffff' : '#6366f1',
                  }"
                ></i>
              </view>
              <text class="category-name">{{ category.name }}</text>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 可用应用列表 -->
      <view class="apps-section">
        <view class="apps-header">
          <view class="header-icon">
            <i
              class="iconfont icon-gongzuotai"
              style="font-size: 18px; color: #6366f1"
            ></i>
          </view>
          <text class="section-title">应用列表</text>
          <text class="app-count">({{ filteredApps.length }})</text>
        </view>

        <!-- 加载状态 -->
        <view v-if="loading" class="loading-state">
          <uni-icons type="spinner-cycle" size="32" color="#6366f1"></uni-icons>
          <text class="loading-text">加载中...</text>
        </view>

        <scroll-view v-else class="apps-scroll" scroll-y>
          <view class="apps-grid">
            <view
              v-for="app in filteredApps"
              :key="app.Id"
              :class="[
                'app-card',
                { processing: processingApps.includes(app.Id) },
              ]"
              @click="toggleAppStatus(app.Id)"
            >
              <!-- 应用图标 -->
              <view class="app-icon">
                <i
                  :class="app.Icon"
                  style="font-size: 32px; color: #ffffff"
                ></i>
              </view>
              <!-- 应用信息 -->
              <view class="app-info">
                <text class="app-name">{{ app.Text }} </text>
                <text
                  v-if="checkAppAdded(app.Id)"
                  class="app-status-text added"
                >
                  已添加
                </text>
                <text v-else class="app-status-text not-added"> 未添加 </text>
              </view>

              <!-- 操作按钮 -->
              <view class="app-action">
                <view
                  v-if="processingApps.includes(app.Id)"
                  class="processing-icon"
                >
                  <uni-icons
                    type="spinner-cycle"
                    size="20"
                    color="#6366f1"
                  ></uni-icons>
                </view>
                <view v-else-if="checkAppAdded(app.Id)" class="remove-btn">
                  <uni-icons type="minus" size="20" color="#ffffff"></uni-icons>
                </view>
                <view v-else class="add-btn">
                  <uni-icons type="plus" size="20" color="#ffffff"></uni-icons>
                </view>
              </view>
            </view>
          </view>

          <!-- 空状态 -->
          <view v-if="filteredApps.length === 0" class="empty-state">
            <uni-icons type="info" size="48" color="#d1d5db"></uni-icons>
            <text class="empty-text">暂无应用</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </XenPageLayout>
</template>

<script lang="ts" setup>
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import useMenuApi from "./api/index";
import { ref, computed, onMounted } from "vue";
import type { IMenu } from "../login/api/interface";
import type { ISearchResult } from "./api/interface";
import {
  useMenuData,
  filterApps,
  isAppAdded,
  handleSearch as handleSearchUtil,
  handleCategorySelect,
  getMenuCategoryIcon,
} from "../../utils/menu";

// 搜索关键词
const searchKeyword = ref("");

// 选中的分类
const selectedCategory = ref("all");

// 加载状态
const loading = ref(false);

// 正在处理的应用ID列表
const processingApps = ref<string[]>([]);

// 已添加的应用列表
const addedApps = ref<ISearchResult[]>([]);

// 菜单数据
const menuData = ref<{
  menuCategories: any[];
  flatMenus: IMenu[];
  filteredMenuCategories: any[];
}>({
  menuCategories: [],
  flatMenus: [],
  filteredMenuCategories: [],
});

// API 实例
const menuApi = useMenuApi();

// 显示的分类列表（包含"全部"选项）
const displayCategories = computed(() => {
  const categories = [{ id: "all", name: "全部", icon: "icon-gongwenbao" }];

  // 将过滤后的菜单分类转换为显示分类
  menuData.value.filteredMenuCategories.forEach((category, index) => {
    categories.push({
      id: category.category.Id,
      name: category.category.Text,
      icon:
        category.category.Icon ||
        getMenuCategoryIcon(category.category.Text, index),
    });
  });

  return categories;
});

// 过滤后的应用列表
const filteredApps = computed(() => {
  return filterApps(
    [],
    searchKeyword.value,
    selectedCategory.value,
    menuData.value.filteredMenuCategories,
  );
});

// 检查应用是否已添加
const checkAppAdded = (appId: string) => {
  const result = isAppAdded(appId, addedApps.value);

  return result;
};

// 选择分类
const selectCategory = (categoryId: string) => {
  handleCategorySelect(categoryId, (id) => {
    selectedCategory.value = id;
  });
};

// 搜索处理
const handleSearch = () => {
  handleSearchUtil(searchKeyword.value);
};

// 切换应用状态（添加/移除）
const toggleAppStatus = async (appId: string) => {
  console.log("点击应用:", appId);
  console.log("当前已添加应用:", addedApps.value);
  console.log("正在处理的应用:", processingApps.value);

  // 如果正在处理，不允许再次点击
  if (processingApps.value.includes(appId)) {
    console.log("应用正在处理中，忽略点击");
    return;
  }

  const isAdded = checkAppAdded(appId);
  console.log("应用是否已添加:", isAdded);

  if (isAdded) {
    console.log("准备移除应用:", appId);
    await removeApp(appId);
  } else {
    console.log("准备添加应用:", appId);
    await addApp(appId);
  }
};

// 添加应用
const addApp = async (appId: string) => {
  const app = menuData.value.flatMenus.find((menu) => menu.Id === appId);
  if (!app) {
    console.log("未找到应用:", appId);
    return;
  }

  console.log("开始添加应用:", app);

  try {
    // 添加到处理列表
    processingApps.value.push(appId);
    console.log("添加到处理列表:", processingApps.value);

    const addParams = {
      Entity: {
        MenuIcon: app.Icon || "",
        MenuId: app.Id,
        MenuName: app.Text,
        MenuUrl: app.Url || "",
        SortOrder: 0,
      },
    };

    console.log("添加参数:", addParams);
    const response = await menuApi.add(addParams);
    console.log("添加响应:", response);

    // 接口没有状态码，只要不抛异常就认为成功
    // 重新加载已添加的应用（不显示loading）
    await loadAddedApps(false);

    // 添加成功后显示提示
    uni.showToast({
      title: "添加成功",
      icon: "success",
      duration: 1500,
    });
  } catch (error) {
    console.error("添加应用出错:", error);
    uni.showToast({
      title: "添加失败",
      icon: "error",
      duration: 1500,
    });
  } finally {
    // 从处理列表移除
    const index = processingApps.value.indexOf(appId);
    if (index > -1) {
      processingApps.value.splice(index, 1);
    }
    console.log("从处理列表移除:", processingApps.value);
  }
};

// 移除应用
const removeApp = async (appId: string) => {
  const addedApp = addedApps.value.find((app) => app.MenuId === appId);
  if (!addedApp) {
    console.log("未找到已添加的应用:", appId);
    return;
  }

  console.log("开始移除应用:", addedApp);

  try {
    // 添加到处理列表
    processingApps.value.push(appId);
    console.log("添加到处理列表:", processingApps.value);

    const response = await menuApi.delete([addedApp.ID]);
    console.log("移除响应:", response);

    // 接口没有状态码，只要不抛异常就认为成功
    // 重新加载已添加的应用（不显示loading）
    await loadAddedApps(false);

    // 移除成功后显示提示
    uni.showToast({
      title: "移除成功",
      icon: "success",
      duration: 1500,
    });
  } catch (error) {
    console.error("移除应用出错:", error);
    uni.showToast({
      title: "移除失败",
      icon: "error",
      duration: 1500,
    });
  } finally {
    // 从处理列表移除
    const index = processingApps.value.indexOf(appId);
    if (index > -1) {
      processingApps.value.splice(index, 1);
    }
    console.log("从处理列表移除:", processingApps.value);
  }
};

// 查询已添加的应用
const loadAddedApps = async (showLoading: boolean = true) => {
  try {
    if (showLoading) {
      loading.value = true;
    }

    const response = await menuApi.search({
      Limit: 1000,
      Page: 1,
    });

    console.log("查询已添加应用响应:", response);
    // 接口没有状态码，只要不抛异常就认为成功
    addedApps.value = response.Data || [];
    console.log("已添加的应用列表:", addedApps.value);
  } catch (error) {
    console.error("查询已添加应用出错:", error);
    addedApps.value = [];
  } finally {
    if (showLoading) {
      loading.value = false;
    }
  }
};

onMounted(async () => {
  const { menuCategories, flatMenus, filteredMenuCategories } = useMenuData();

  menuData.value = {
    menuCategories,
    flatMenus,
    filteredMenuCategories,
  };

  console.log("菜单数据加载完成:", {
    原始分类数量: menuCategories.length,
    过滤后分类数量: filteredMenuCategories.length,
    应用总数: flatMenus.length,
    过滤后应用数量: filteredMenuCategories.flatMap((cat) => cat.children)
      .length,
    过滤后菜单分类: filteredMenuCategories,
  });

  // 初始加载时显示loading
  await loadAddedApps(true);
});
</script>

<style lang="scss" scoped>
.menu-container {
  flex: 1;
  background: #ffffff;
  border-radius: 24px 24px 0 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .search-section {
    padding: 20px;
    background: #ffffff;
    border-bottom: 1px solid #f0f0f0;

    .search-box {
      display: flex;
      align-items: center;
      background: #f8f9fa;
      border-radius: 12px;
      padding: 12px 16px;
      gap: 8px;

      .search-input {
        flex: 1;
        font-size: 16px;
        color: #333;
        background: transparent;
        border: none;
        outline: none;

        &::placeholder {
          color: #999;
        }
      }
    }
  }

  .category-section {
    padding: 20px;
    background: #ffffff;
    border-bottom: 1px solid #f0f0f0;

    .category-header {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      gap: 8px;

      .header-icon {
        width: 32px;
        height: 32px;
        border-radius: 8px;
        background: rgba(99, 102, 241, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .section-title {
        color: #1a1a1a;
        font-size: 16px;
        font-weight: 600;
        flex: 1;
      }
    }

    .category-list {
      width: 100%;
      white-space: nowrap;

      .category-wrapper {
        display: flex;
        gap: 12px;
        padding-right: 20px; // 右侧留出一些空间

        .category-item {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 8px 16px;
          background: #f8f9fa;
          border-radius: 20px;
          border: 2px solid transparent;
          transition: all 0.3s ease;
          flex-shrink: 0; // 防止项目被压缩

          &.active {
            background: #6366f1;
            border-color: #6366f1;

            .category-name {
              color: #ffffff;
            }
          }

          .category-icon {
            display: flex;
            align-items: center;
            justify-content: center;
          }

          .category-name {
            font-size: 14px;
            color: #666;
            white-space: nowrap;
          }

          &.active .category-name {
            color: #ffffff;
          }
        }
      }
    }
  }

  .apps-section {
    flex: 1;
    padding: 20px;
    display: flex;
    flex-direction: column;
    min-height: 0;

    .apps-header {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      gap: 8px;

      .header-icon {
        width: 32px;
        height: 32px;
        border-radius: 8px;
        background: rgba(99, 102, 241, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .section-title {
        color: #1a1a1a;
        font-size: 16px;
        font-weight: 600;
        flex: 1;
      }

      .app-count {
        font-size: 14px;
        color: #999;
        font-weight: normal;
      }
    }

    .loading-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 40px;
      color: #6366f1;

      .loading-text {
        margin-top: 16px;
        font-size: 16px;
      }
    }

    .apps-scroll {
      flex: 1;
      min-height: 0;
    }

    .apps-grid {
      display: grid;
      grid-template-columns: 1fr;
      gap: 12px;

      .app-card {
        display: flex;
        align-items: center;
        background: #ffffff;
        border-radius: 16px;
        padding: 16px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        border: 2px solid transparent;
        transition: all 0.3s ease;

        &.processing {
          opacity: 0.7;
          pointer-events: none;
        }

        &:active {
          transform: scale(0.98);
        }

        .app-icon {
          width: 48px;
          height: 48px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
          margin-right: 16px;
          flex-shrink: 0;

          .icon-img {
            width: 32px;
            height: 32px;
            border-radius: 8px;
          }
        }

        .app-info {
          flex: 1;
          min-width: 0;
          display: flex;
          flex-direction: column;
          gap: 4px;

          .app-name {
            font-size: 16px;
            font-weight: 600;
            color: #333;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .app-status-text {
            font-size: 12px;
            font-weight: 500;
            margin-top: 4px;

            &.added {
              color: #10b981;
            }

            &.not-added {
              color: #f59e0b;
            }
          }
        }

        .app-action {
          display: flex;
          align-items: center;
          justify-content: center;
          flex-shrink: 0;

          .processing-icon {
            width: 36px;
            height: 36px;
            border-radius: 18px;
            background: #f0f0f0;
            display: flex;
            align-items: center;
            justify-content: center;
            animation: spin 1s linear infinite;
          }

          .add-btn {
            width: 36px;
            height: 36px;
            border-radius: 18px;
            background: #10b981;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;

            &:active {
              background: #059669;
            }
          }

          .remove-btn {
            width: 36px;
            height: 36px;
            border-radius: 18px;
            background: #ef4444;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;

            &:active {
              background: #dc2626;
            }
          }
        }
      }
    }

    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 40px;
      color: #999;

      .empty-text {
        margin-top: 16px;
        font-size: 16px;
      }
    }
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
